# encoding=utf-8
import redis
from constant.const import const
from config.yml import yml
import datetime
import time


class cache(object):
    def __init__(self):
        y = yml().redix
        pool = redis.ConnectionPool(host = y.host, port = y.port, db = y.database, password = y.password)
        self.cache = redis.Redis(connection_pool = pool, decode_responses = True, charset = 'UTF-8', encoding = 'UTF-8')

    def map(self, f, k, v):
        self.cache.hset(f, k, v)

    def string(self, k, v, time, type):
        if time != const.time:
            if type == const.ex:
                self.cache.set(k, v, ex = time)
            else:
                self.cache.set(k, v, px = time)
        else:
            self.cache.set(k, v)

    def delete(self, name, url, type):
        if type == const.map:
            return self.cache.hdel(name, url)
        elif type == const.string:
            return self.cache.delete(name)
        elif type == const.list:
            return self.cache.lpop(name)
        elif type == const.set:
            return self.cache.spop(name)
        else:
            return self.cache.zrem(name)

    # def bit(self, name, url, type):
    #     if type == const.set:
    #         self.cache.setbit(name, url, 1)
    #     elif type == const.get:
    #         self.cache.getbit(name, url)

    def get(self, name, url, type):
        if type == const.map:
            return self.cache.hget(name, url)
        elif type == const.string:
            return self.cache.get(name)

    def get_all_map(self, k):
        return self.cache.hgetall(k).items()

    def get_map(self, k):
        return self.cache.hgetall(k)

    def time(self, k, v, t):
        if v != 0 and t is None:
            self.cache.expire(k, v)
        if v == 0 and t is not None:
            split = t.split("-")
            extime = datetime.datetime(int(split[0]), int(split[1]), int(split[2]), int(split[3]), int(split[4]), int(split[5]))
            extime.strftime('%Y-%m-%d %H:%M:%S %f')
            self.cache.expireat(k, extime)

    def contain(self, k):
        return self.cache.exists(k)

    def list(self, k, v, type):
        if type == const.list:
            self.cache.lpush(k, v)
        elif type == const.set:
            self.cache.sadd(k, v)
        elif type == const.zset:
            self.cache.zadd(k, v)

    def incr(self, k):
        self.cache.incr(k)

# c = cache()
# c.string("sss", 1, 0, const.px)
# time.sleep(3)
# c.incr("sss")
# print(str(c.get('sss', None, const.string),encoding='utf-8'))
# c.delete("newkey", None, const.string)
# c.delete("users-subscribed", None, const.string)
# c.time(1, 1, 1)
# c.map('ex1', "k1", "v1")
# c.time('ex1', 10, None)
# c.time('ex1', 0, "2023-3-9-15-40-00")


# s = str(c.get('k', None, const.string), encoding='utf-8')
# k = int(str(c.get('k', None, const.string), encoding='utf-8'))
# print(type(k))
